#ifndef _M_UTIL_H
#define _M_UTIL_H

// 工具类

#include <iostream>
#include <string>
#include <ctime>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<fstream>
class Date
{

public:
    static size_t Now()
    {
        return (size_t)time(nullptr);
    }
};

class File
{

public:
    static bool Isexit(const std::string &pathname)
    {
        // return access(pathname.c_str(),F_OK)==0;
        struct stat st;
        return stat(pathname.c_str(), &st) == 0;
    }
    // 提取文件路径:
    //  a/b/c/t.c
    //  /a/t.c
    static std::string Getpath(const std::string &name)
    {
        if (name.empty())
            return ".";
        size_t pos = name.find_last_of("/\\");
        if (pos == std::string::npos)
            return ".";
        return name.substr(0, pos + 1); // 一般发生
        // 拿到 /a/
    }

    // a/b/c/   /a/b/  ../a/b/
    static void Createdir(const std::string &pathname)
    {
        if (pathname.empty())
            return;
        if (Isexit(pathname))
            return;

        int start=0, pos = 0;
        while (start < pathname.size())
        {
            pos = pathname.find_first_of("/\\",start);
            if (pos == std::string::npos) // 很少发生
            {
                mkdir(pathname.c_str(), 0755);
                return;
            }
            if (pos == start)
            {
                start = pos + 1;
                continue;
            }
            std::string current = pathname.substr(0,pos);//这里创建目录必须从0开始截取
            //../a/b
            if (Isexit(current))
            {
                start = pos + 1;
                continue;
            }
            if (current == "." || current == "..")
            {
                start = pos + 1;
                continue;
            }
            mkdir(current.c_str(), 0755);
            start = pos + 1;
        }
    }
};

#endif